{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "from transformers import PreTrainedTokenizerFast\n",
    "from sklearn.feature_extraction.text import CountVectorizer\n",
    "from sklearn.naive_bayes import ComplementNB"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [],
   "source": [
    "tokenizer = PreTrainedTokenizerFast(tokenizer_file='bpe-400k')\n",
    "vocabulary = list(tokenizer.vocab.keys())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "CPU times: user 1 ms, sys: 918 µs, total: 1.92 ms\n",
      "Wall time: 947 µs\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "'tak Ġsuka Ġayam 1 2 3 1 2 4 1 2 3'"
      ]
     },
     "execution_count": 3,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "%%time\n",
    "strings = [\n",
    "    'tak suka ayam123124123',\n",
    "    'tak suka ayam'\n",
    "]\n",
    "subs = [' '.join(tokenizer.tokenize(s)) for s in strings]\n",
    "subs[0]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "/home/husein/.local/lib/python3.8/site-packages/sklearn/feature_extraction/text.py:1330: UserWarning: Upper case characters found in vocabulary while 'lowercase' is True. These entries will not be matched with any documents\n",
      "  warnings.warn(\n"
     ]
    }
   ],
   "source": [
    "bow = CountVectorizer(vocabulary = vocabulary, token_pattern = r'[\\S]+').fit(subs)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [],
   "source": [
    "import pickle\n",
    "\n",
    "with open('bow.pkl', 'wb') as fopen:\n",
    "    pickle.dump(bow, fopen)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [],
   "source": [
    "lang_labels_v2 = {\n",
    "    0: 'standard-english',\n",
    "    1: 'local-english',\n",
    "    2: 'manglish',\n",
    "    3: 'standard-indonesian',\n",
    "    4: 'socialmedia-indonesian',\n",
    "    5: 'standard-malay',\n",
    "    6: 'local-malay',\n",
    "    7: 'standard-mandarin',\n",
    "    8: 'local-mandarin',\n",
    "    9: 'other',\n",
    "}\n",
    "\n",
    "lang_labels_v2_rev = {v: k for k, v in lang_labels_v2.items()}"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "huggingface/tokenizers: The current process just got forked, after parallelism has already been used. Disabling parallelism to avoid deadlocks...\n",
      "To disable this warning, you can either:\n",
      "\t- Avoid using `tokenizers` before the fork if possible\n",
      "\t- Explicitly set the environment variable TOKENIZERS_PARALLELISM=(true | false)\n",
      "10500345 shuf-train-fasttext.txt\n"
     ]
    }
   ],
   "source": [
    "!wc -l shuf-train-fasttext.txt"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "10500345it [35:49, 4886.03it/s] \n"
     ]
    }
   ],
   "source": [
    "from tqdm import tqdm\n",
    "\n",
    "batch_size = 200000\n",
    "\n",
    "x, y = [], []\n",
    "train = False\n",
    "\n",
    "nb = ComplementNB()\n",
    "\n",
    "with open('shuf-train-fasttext.txt') as fopen:\n",
    "    for l in tqdm(fopen):\n",
    "        splitted = l.split()\n",
    "        label = splitted[0].replace('__label__', '')\n",
    "        x.append(' '.join(splitted[1:]))\n",
    "        y.append(lang_labels_v2_rev[label])\n",
    "        if len(x) >= batch_size:\n",
    "            subs = [' '.join(tokenizer.tokenize(s)) for s in x]\n",
    "            subs = bow.transform(subs)\n",
    "            if not train:\n",
    "                nb = nb.fit(subs, y)\n",
    "                train = True\n",
    "            else:\n",
    "                nb = nb.partial_fit(subs, y)\n",
    "            \n",
    "            x, y = [], []"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {},
   "outputs": [],
   "source": [
    "with open('nb.pkl', 'wb') as fopen:\n",
    "    pickle.dump(nb, fopen)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "<10x400000 sparse matrix of type '<class 'numpy.int64'>'\n",
       "\twith 34 stored elements in Compressed Sparse Row format>"
      ]
     },
     "execution_count": 13,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "subs[:10]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([3, 7, 3, 2, 3, 4, 4, 8, 0, 9])"
      ]
     },
     "execution_count": 14,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "nb.predict(subs[:10])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[1, 0, 6, 8, 6, 7, 4, 5, 9, 1]"
      ]
     },
     "execution_count": 15,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "y[:10]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.8.10"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
